/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 *
 * 我的工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    TouchableOpacity, TouchableHighlight,
    RefreshControl,
    ScrollView,
    Modal, StyleSheet, Platform, BackHandler, ToastAndroid,NetInfo,NativeModules
} from 'react-native';
import {connect} from 'react-redux';
import {
    COLOR_GRAY_BACKGROUND, COLOR_THEME,
    COLOR_WHITE,COLOR_HEADER_END,COLOR_HEADER_START,
    FONT_COLOR_SUB_TITLE,
    FONT_COLOR_TITLE,
    FONT_SIZE_14
} from "../constant/PHColors";
import ImageAndTextCellView from "../component/ImageAndTextCellView/ImageAndTextCellView";
import OffWorkView from "../component/OffWorkView/OffWorkView";
import {SCREEN_WIDTH} from "../constant/PHScreen";
import AntDesign from "react-native-vector-icons/AntDesign";
import JPushModal from "../component/JPushModalView/JPushModalView";
import User from "../model/User/User";
import global from "../configuration/global";
import {orderEventGetinfo} from "../component/JPushModalView/Action";
import Sound from 'react-native-sound';
import {whskMenuMain,createFtpTimer} from "../screen/login/LoginScreen/Actions";
import {FetchStatus} from "../configuration/RequestConfiguration";
import {ReturnStatus} from "../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../component/Message/Action";
import codePush from "react-native-code-push";
import {AppRequestPath, ContextPath} from "../configuration/AppConfig";
import {API_UPLOADIMG} from "../constant/API";

class HousekeeperMainNavigator extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: navigation.getParam('username'),
        headerLeft: <View/>,
        headerRight: <OffWorkView navigation={navigation}/>
    });

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            JPushModalVisiable:false,
            WebSocketData:[],
            userid:'',
            orderType:[],
            random:1,
            redpoint:{},
            isRefreshing:false,
        };

        User.getUser(user => {
            this.props.navigation.setParams({username:user.username+'-'+user.userid});
        });

        global.AppType = '房务';

        setInterval(() => {
            let WebSocketData = global.WebSocketData.data;
            let WebSocketData_new = [];
            let orderType = [];
            let random = global.WebSocketData.random;

            let {dispatch} = this.props;
            User.getUser(user => {
                if (user&&user.token) {
                    WebSocketData.map((item, index) => {
                        if(item.userid.toLowerCase()===user.userid.toLowerCase() && item.jpush_alias===""){
                            WebSocketData_new.push(item)
                            orderType.push(item.ordertype)
                        }
                    })
                    if(global.WebSocketData.random !== global.WebSocketData.newrandom && JSON.stringify(WebSocketData_new)!== '[]' && global.AppType==="房务"){
                        console.log("=============播报语音初始化=============")
                        let demoAudio = ContextPath()+"/attach/mobileBell.mp3";//支持众多格式
                        let s = new Sound(demoAudio,'', (e) => {
                            console.log(e);
                            if (e) {
                                console.log('播放失败');
                                return
                            }
                            console.log("=============播报语音提醒=============")
                            s.play(() => s.release());
                        });
                        // s.play(() => s.release());
                        // s.play();
                        // s.play(() => s.release());
                        global.WebSocketData.newrandom = random;

                        dispatch(whskMenuMain())
                        this.setState({
                            WebSocketData: WebSocketData_new,
                            JPushModalVisiable:true,
                            userid:user.userid,
                            orderType:orderType,
                        })

                    }
                }
            })
        }, 1000)
    }



    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }

        codePush.checkForUpdate(global.CODE_PUSH_KEY).then((update) => {
            if (!update) {
                // ToastAndroid.show('已是最新版本', 1000);//提示
            } else {
                codePush.sync({
                        deploymentKey: global.CODE_PUSH_KEY,
                        updateDialog: {
                            //是否显示更新描述
                            appendReleaseDescription : true ,
                            //更新描述的前缀。 默认为"Description"
                            descriptionPrefix : "更新内容：" ,
                            //强制更新按钮文字，默认为continue
                            mandatoryContinueButtonLabel : "立即更新" ,
                            //强制更新时的信息. 默认为"An update is available that must be installed."
                            mandatoryUpdateMessage : "必须更新后才能使用" ,
                            //非强制更新时，按钮文字,默认为"ignore"
                            optionalIgnoreButtonLabel : '稍后' ,
                            //非强制更新时，确认按钮文字. 默认为"Install"
                            optionalInstallButtonLabel : '后台更新' ,
                            //非强制更新时，检查到更新的消息文本
                            optionalUpdateMessage : '有新版本了，是否更新？' ,
                            //Alert窗口的标题
                            title : '更新提示'
                        },
                        installMode: codePush.InstallMode.IMMEDIATE,
                    },
                    (status) => {
                        switch (status) {
                            case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                                console.log("DOWNLOADING_PACKAGE");
                                break;
                            case codePush.SyncStatus.INSTALLING_UPDATE:
                                console.log("INSTALLING_UPDATE");
                                break;
                        }
                    },
                    (progress) => {
                        console.log(progress.receivedBytes + " of " + progress.totalBytes + " received.");
                    }
                );
            }
        })
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;
        if (nextProps.onWHSKMenuMain !== this.props.onWHSKMenuMain && nextProps.onWHSKMenuMain.fetchStatus === FetchStatus.Success) {
            if (nextProps.onWHSKMenuMain.RETURN === ReturnStatus.Success) {
                let menumain = nextProps.onWHSKMenuMain.menumain;
                let json = {}
                if(menumain.length>0){
                    menumain.map((item, index) => {
                        if(item.name==='即时工单'){
                            json.jsgd = item.counts
                        }else if(item.name==='客房清洁'){
                            json.kfqj = item.counts
                        }else if(item.name==='定期工单'){
                            json.dqgd = item.counts
                        }else if(item.name==='培训工单'){
                            json.pxgd = item.counts
                        }
                    })
                }

                this.setState({
                    redpoint: json,
                    isRefreshing: false
                });
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onWHSKMenuMain.MSG))
            }
        }

        if (nextProps.onCreateFtpTimer !== this.props.onCreateFtpTimer && nextProps.onCreateFtpTimer.fetchStatus === FetchStatus.Success) {
            if (nextProps.onCreateFtpTimer.RETURN === ReturnStatus.Success) {
                console.log("*-+-*-+-*-+-*-+-*"+JSON.stringify(nextProps.onCreateFtpTimer))

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onCreateFtpTimer.MSG))
            }
        }



    }

    // 组件渲染后调用
    componentDidMount() {
        // this.props.navigation.navigate('MainNavigator');
        let {dispatch} = this.props;
        dispatch(whskMenuMain());

        // dispatch(createFtpTimer())

        // 'hotelId':global.hotelId,
        //     'websocketName':"websocketroomsview",
        //     'fu':"RetrieveRoomsViewAs",
        //     'jn':JSON.stringify({
        //     "wherestatus":{"All":"1"},
        //     "arg":{"arg":"房务"},
        //     "where":{"building":"","rmtype":"","floor":"","allSearch":"","source":"","market":"","features":"","grno":""}
        // }),
        //     'json':JSON.stringify({"output":{"json":"null"}}),
        //     'type':"proc"

        let data = new FormData();
        data.append("hotelId", global.hotelId);
        data.append("websocketName", 'websocketroomsview');
        data.append("fu", 'RetrieveRoomsViewAs');
        data.append("jn", JSON.stringify({
                "wherestatus":{"All":"1"},
                "arg":{"arg":"房务"},
                "where":{"building":"","rmtype":"","floor":"","allSearch":"","source":"","market":"","features":"","grno":""}
            }),);
        data.append("json", JSON.stringify({"output":{"json":"null"}}));
        data.append("type", 'proc');
        try {
            fetch(ContextPath()+ '/frontofficeTimer/creTimer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data;charset=utf-8'
                },
                body: data
            }).then(function(response) {
                return response.json();
            }).then(data=>{
               console.log(JSON.stringify(data))
            })
        } catch (err) {
            console.log(err)
        }

    }

    onBackAndroid = () =>{
        if(this.props.navigation.isFocused()){//判断   该页面是否处于聚焦状态
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                BackHandler.exitApp();//直接退出APP
            }else{
                this.lastBackPressed = Date.now();
                ToastAndroid.show('再按一次退出应用', 1000);//提示
                return true;
            }
        }
    };


    render() {
        return (
            <SafeAreaView style={styles.body}>

                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh}
                            // colors={['#ccc']}
                            // progressBackgroundColor='#459cff'
                        />
                    }
                    style={styles.body}
                >

                    <View style={styles.headerContainer}>
                        <Text style={styles.headerText}>
                            我的任务
                        </Text>
                    </View>


                    <View style={styles.myMissionView}>
                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            this.props.navigation.navigate('WorkOrderListScreen')
                        }}>
                            <View style={styles.myMissionBox}>
                                <Image style={styles.myMissionImage} source={require('../resource/job/work_gcgl.png')}/>
                                {
                                    (this.state.redpoint.hasOwnProperty('jsgd') &&this.state.redpoint['jsgd']>0) && (
                                        <View style={styles.rightBox}>
                                            <Text style={styles.numText}>
                                                {this.state.redpoint['jsgd']}
                                            </Text>
                                        </View>
                                    )
                                }
                                <View  style={styles.myMissionTextView}>
                                    <Text style={styles.myMissionText}>
                                        即时工单
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>

                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            this.props.navigation.navigate('roomCleanScreen')
                        }}>
                            <View style={styles.myMissionBox}>
                                <Image style={styles.myMissionImage} source={require('../resource/job/work_kfgl.png')}/>
                                {
                                    (this.state.redpoint.hasOwnProperty('kfqj') &&this.state.redpoint['kfqj']>0) && (
                                        <View style={styles.rightBox}>
                                            <Text style={styles.numText}>
                                                {this.state.redpoint['kfqj']}
                                            </Text>
                                        </View>
                                    )
                                }
                                <View  style={styles.myMissionTextView}>
                                    <Text style={styles.myMissionText}>
                                        客房清洁
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>
                    </View>
                    <View style={styles.myMissionView}>

                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            // this.props.navigation.navigate('roomChangeReport')
                            this.props.navigation.navigate('RoomDiskScreen');
                        }}>
                            <View style={styles.myMissionBox}>
                                <Image style={styles.myMissionImage} source={require('../resource/job/work_wdgd.png')}/>
                                <View  style={styles.myMissionTextView}>
                                    <Text style={styles.myMissionText}>
                                        房态盘
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>
                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            // this.props.navigation.navigate('PersonnelStatusScreen')
                            this.props.navigation.navigate('roomHistoryReport')
                        }}>
                            <View style={styles.myMissionBox}>
                                <Image style={styles.myMissionImage} source={require('../resource/job/work_pxkc.png')}/>
                                {
                                    (this.state.redpoint.hasOwnProperty('pxgd')&&this.state.redpoint['pxgd']>0) && (
                                        <View style={styles.rightBox}>
                                            <Text style={styles.numText}>
                                                {this.state.redpoint['pxgd']}
                                            </Text>
                                        </View>
                                    )
                                }
                                <View  style={styles.myMissionTextView}>
                                    <Text style={styles.myMissionText}>
                                        房间历史
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>
                    </View>

                    <View style={styles.headerContainer}>
                        <Text style={styles.headerText}>
                            通用
                        </Text>
                    </View>

                    <View style={styles.usualView}>
                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            // this.props.navigation.navigate('CreateRepairWorkOrderScreen')
                            this.props.navigation.navigate('WorkOrderScreen')
                        }}>
                            <View style={styles.usualViewBox}>
                                <View  style={styles.usualViewImage}>
                                    <AntDesign name={'tool'} size={35} style={{color: 'white'}}/>
                                </View>

                                <View  style={styles.usualViewTextView}>
                                    <Text style={styles.usualViewText}>
                                        工程
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>
                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            // this.props.navigation.navigate('RoomDiskScreen');
                            // this.props.navigation.navigate('allOrderScreen');
                            this.props.navigation.navigate('RoomOrderScreen');
                        }}>
                            <View style={styles.usualViewBox}>
                                <View  style={styles.usualViewImage}>
                                    <AntDesign name={'appstore-o'} size={40} style={{color: 'white'}}/>
                                </View>

                                <View  style={styles.usualViewTextView}>
                                    <Text style={styles.usualViewText}>
                                        房务
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>
                        {/*<TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            this.props.navigation.navigate('RoomsViewScreen');
                        }}>
                            <View style={styles.usualViewBox}>
                                <View  style={styles.usualViewImage}>
                                    <AntDesign name={'appstore-o'} size={40} style={{color: 'white'}}/>
                                </View>

                                <View  style={styles.usualViewTextView}>
                                    <Text style={styles.usualViewText}>
                                        房态盘
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>*/}
                        <TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{
                            codePush.checkForUpdate(global.CODE_PUSH_KEY).then((update) => {
                                if (!update) {
                                    ToastAndroid.show('已是最新版本', 1000);//提示
                                } else {
                                    codePush.sync({
                                            deploymentKey: global.CODE_PUSH_KEY,
                                            updateDialog: {
                                                //是否显示更新描述
                                                appendReleaseDescription : true ,
                                                //更新描述的前缀。 默认为"Description"
                                                descriptionPrefix : "更新内容：" ,
                                                //强制更新按钮文字，默认为continue
                                                mandatoryContinueButtonLabel : "立即更新" ,
                                                //强制更新时的信息. 默认为"An update is available that must be installed."
                                                mandatoryUpdateMessage : "必须更新后才能使用" ,
                                                //非强制更新时，按钮文字,默认为"ignore"
                                                optionalIgnoreButtonLabel : '稍后' ,
                                                //非强制更新时，确认按钮文字. 默认为"Install"
                                                optionalInstallButtonLabel : '后台更新' ,
                                                //非强制更新时，检查到更新的消息文本
                                                optionalUpdateMessage : '有新版本了，是否更新？' ,
                                                //Alert窗口的标题
                                                title : '更新提示'
                                            },
                                            installMode: codePush.InstallMode.IMMEDIATE,
                                        },
                                        (status) => {
                                            switch (status) {
                                                case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                                                    console.log("DOWNLOADING_PACKAGE");
                                                    break;
                                                case codePush.SyncStatus.INSTALLING_UPDATE:
                                                    console.log("INSTALLING_UPDATE");
                                                    break;
                                            }
                                        },
                                        (progress) => {
                                            console.log(progress.receivedBytes + " of " + progress.totalBytes + " received.");
                                        }
                                    );
                                }
                            })
                        }}>
                            <View style={styles.usualViewBox}>
                                <View  style={styles.usualViewImage}>
                                    <AntDesign name={'download'} size={40} style={{color: 'white'}}/>
                                </View>

                                <View  style={styles.usualViewTextView}>
                                    <Text style={styles.usualViewText}>
                                        下载更新
                                    </Text>
                                </View>
                            </View>
                        </TouchableHighlight>
                    </View>

                    {/*<TouchableHighlight underlayColor={'#ffffff'} onPress={()=>{*/}
                            {/*this.props.navigation.navigate('setOOOSScreen',{room:'712'});*/}
                        {/*}}>*/}
                            {/*<View style={styles.usualViewBox}>*/}
                                {/*<View  style={styles.usualViewImage}>*/}
                                    {/*<AntDesign name={'appstore-o'} size={40} style={{color: 'white'}}/>*/}
                                {/*</View>*/}

                                {/*<View  style={styles.usualViewTextView}>*/}
                                    {/*<Text style={styles.usualViewText}>*/}
                                        {/*测试*/}
                                    {/*</Text>*/}
                                {/*</View>*/}
                            {/*</View>*/}
                        {/*</TouchableHighlight>*/}

                    <JPushModal JPushModalVisiable={this.state.JPushModalVisiable} WebSocketData={this.state.WebSocketData}
                                CloseJPushModal={()=>{
                                    this.onCloseJPushModal()
                                    // s.stop();
                                }}
                                SubmitJPushModal={()=>{
                                    this.onCloseJPushModal()
                                    // s.stop();
                                    if(this.state.orderType.indexOf('清洁检查')>-1){
                                        this.props.navigation.navigate('HousekeeperMainNavigator');
                                        this.props.navigation.navigate('roomCleanScreen');
                                    }else if(this.state.orderType.indexOf('清洁')>-1){
                                        this.props.navigation.navigate('HousekeeperMainNavigator');
                                        this.props.navigation.navigate('roomCleanScreen');
                                    }else{
                                        this.props.navigation.navigate('HousekeeperMainNavigator');
                                        this.props.navigation.navigate('WorkOrderListScreen');
                                    }
                                    let {dispatch} = this.props;
                                    let orderpids_arr = [];
                                    let orderpids = '';
                                    let userid = '';
                                    this.state.WebSocketData.map((item, index) => {
                                        orderpids_arr.push(...item.orderpids.split(","));
                                        userid = item.userid;
                                    })
                                    orderpids = Array.from(new Set(orderpids_arr)).join(',');
                                    let str = {"arg":{"orderpids":orderpids,"userid":userid}}
                                    dispatch(orderEventGetinfo(str));

                                }}
                    />

                </ScrollView>

            </SafeAreaView>
        )
    }

    _onRefresh=()=>{
        this.setState({isRefreshing: true});

        //加载数据
        let {dispatch} = this.props;
        dispatch(whskMenuMain())
    }

    onCloseJPushModal(){
        this.setState({
            JPushModalVisiable:false
        })
    }

}

const styles = StyleSheet.create({
    body: {
        flex: 1,
        backgroundColor: COLOR_GRAY_BACKGROUND
    },

    headerContainer: {
        height: 32,
        backgroundColor: COLOR_GRAY_BACKGROUND,
        justifyContent: 'center',
        alignItems: 'flex-start'
    },

    headerText: {
        fontSize: FONT_SIZE_14,
        color: FONT_COLOR_SUB_TITLE,
        marginLeft: 15
    },

    myMissionView:{
        flex: 1,
        flexDirection: 'row',
        width: SCREEN_WIDTH,
        backgroundColor:'#fff',
        height:150,
        justifyContent: 'space-evenly',
    },

    myMissionBox:{
        flexDirection: 'column',
        justifyContent:'space-evenly',
        alignItems:'center',
        height:150,
        width: 95,
    },

    myMissionImage:{
        width: 95,
        height: 95,
    },

    myMissionTextView:{
        justifyContent:'center',
        alignItems:'center',
    },

    myMissionText:{
        fontSize: 16,
        color:FONT_COLOR_TITLE,
    },

    usualView:{
        flex: 1,
        flexDirection: 'row',
        width: SCREEN_WIDTH,
        backgroundColor:'#fff',
        height:130,
        justifyContent: 'space-evenly',
    },

    usualViewBox:{
        flexDirection: 'column',
        justifyContent:'space-evenly',
        alignItems:'center',
        height:130,
    },

    usualViewTextView:{
        justifyContent:'center',
        alignItems:'center',
    },

    usualViewText:{
        fontSize: 16,
        color:FONT_COLOR_TITLE,
    },

    usualViewImage:{
        width: 65,
        height: 65,
        backgroundColor:'#459cff',
        borderRadius:50,
        justifyContent:'center',
        alignItems:'center',
    },

    rightBox: {
        position:'absolute',
        top:10,
        right:10,
        width: 22,
        height: 22,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'red',
        borderRadius: 11
    },

    numText: {
        fontSize: 12,
        color: '#FFF'
    }
});

const props = state => {
    return {
        onWHSKMenuMain:state.onWHSKMenuMain,
        onCache:state.onCache,
        onCreateFtpTimer:state.onCreateFtpTimer,
    }
};

export default HousekeeperMainNavigator = connect(props)(HousekeeperMainNavigator);